//      smed_un.cpp
//
//      Copyright 2011 mdchaparror <mdchaparror@gmail.com>
//
//      This program is free software; you can redistribute it and/or modify
//      it under the terms of the GNU General Public License as published by
//      the Free Software Foundation; either version 2 of the License, or
//      (at your option) any later version.
//
//      This program is distributed in the hope that it will be useful,
//      but WITHOUT ANY WARRANTY; without even the implied warranty of
//      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//      GNU General Public License for more details.
//
//      You should have received a copy of the GNU General Public License
//      along with this program; if not, write to the Free Software
//      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
//      MA 02110-1301, USA.

#include "smed_un.h"
#include "ui_smed_un.h"
#include <iostream>
#include <QFileDialog>
#include <QImage>
#include <QTimer>
#include <QtGlobal>
#include "comunicacion_serial.h"
#include <QDebug>
double maximoX=10,maximoY=50;
double minimoX=0,minimoY=0;
#ifdef win32

class SleeperThread : public QThread
{
public:
    static void msleep(unsigned long msecs)
    {
        QThread::msleep(msecs);
    }
};
#endif
using namespace std;
QTimer *timer;
smed_un::smed_un(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::smed_un)
{

    ui->setupUi(this);
    inicio();
    ui->textEdit->append(puerto_serie->getPort());




}
void smed_un::inicio()
{


    QSplashScreen splash(QPixmap(":/Imagenes/Imagenes/UNAL-full.jpg"));
    splash.show();
    splash.showMessage("\n Inicializando.. ", Qt::AlignBottom, Qt::blue);
    wait_mil(1000);
    //initializing
    leer_configuracion();
    ui->Ploter->SetLabel("Esfuerzo Vs Deformacion","Esfuerzo","Deformacion");
    ui->Ploter->cargar_configuracion();
    buffer_in.clear();
    splash.showMessage("\n UNIVERSIDAD NACIONAL ", Qt::AlignBottom, Qt::blue);
    wait_mil(1000);
    splash.showMessage("\n FACULTAD DE INGENIERIA", Qt::AlignBottom, Qt::blue);
    wait_mil(1000);
    splash.showMessage("\n INGENIERIA ELECTRONICA", Qt::AlignBottom, Qt::blue);
    wait_mil(1000);
    splash.showMessage("\n MARTIN DANIEL CHAPARRO RUIZ", Qt::AlignBottom, Qt::blue);
    wait_mil(1000);
    puerto_serie = new QPort();
    puerto_serie->setPort(global::Puerto);
    puerto_serie->setBaudRate(QPort::BAUD57600);
    puerto_serie->setDataBits(QPort::DATA_8);
    puerto_serie->setParity(QPort::PAR_NONE);
    puerto_serie->setStopBits(QPort::STOP_2);
    puerto_serie->setFlowControl(QPort::FLOW_OFF);
    puerto_serie->setTimeout(0,1);
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(CapturaPortSerie()));
    timer->stop();
    connect(puerto_serie,SIGNAL(newData(QByteArray)),this,SLOT(nuevo_dato_serie(QByteArray)));
    splash.showMessage("Puerto: "+puerto_serie->getPort(), Qt::AlignBottom, Qt::blue);
    wait_mil(500);


}
smed_un::~smed_un()
{

    delete ui;
    guardar_configuracion();

    QSplashScreen splash(QPixmap(":/Imagenes/Imagenes/UNAL-full.jpg"));
    splash.show();
    splash.showMessage("\n *cerrando...", Qt::AlignBottom, Qt::blue);
    wait_mil(100);
    splash.showMessage("\n *cerrando puerto serie", Qt::AlignBottom, Qt::blue);
    puerto_serie->close();
     wait_mil(100);
}
void smed_un::on_Cargar_archivo_clicked()
{
    QString temp;
    double y,x;
    int separador;
    QString fileName = QFileDialog::getOpenFileName(this,"cargar archivo","","CVS(*.cvs)");
    statusBar()->showMessage(tr("archivo: %1").arg(fileName),2000);
    curve1.clear();
    on_Clear_graphics_clicked();
    QFile file(fileName);
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    QTextStream in(&file);
    while (!in.atEnd())
    {
        temp=in.readLine();
        if(temp.startsWith('#'))continue;
        separador=temp.indexOf('\t');
        y=temp.mid(separador,temp.length()-separador).toDouble();
        x=temp.left(separador).toDouble();
        curve1.append(QPointF(x,y));
        idatos_tabla(QPointF(x,y));
    }

    file.close();

    ajustar_ejes();


}
void smed_un::on_guardar_grafica_clicked()
{
    QString filename=QFileDialog::QFileDialog::getSaveFileName(this, tr("Save File"),"untitled.png",tr("Images (*.png)"));
    QImage im(ui->Ploter->size(),QImage::Format_RGB16);
    QPainter painter(&im);
    ui->Ploter->render(&painter);
    im.save(filename);
    statusBar()->showMessage(tr("Imagen: %1 guardada").arg(filename),2000);

}
void smed_un::nuevo_dato_serie(const QByteArray &DatoR)
{
    QString temp,dato;
    double y,x;
    int separador;


        dato=puerto_serie->FormatData(DatoR,'t'," ");



    if(dato!="\n")
        buffer_in.append(dato);
    else
    {
        temp=QString(buffer_in);
       // ui->textEdit->append(temp);
        emit nuevo_dato(temp);
        separador=temp.indexOf(global::Separador_texto);
        y=temp.mid(separador,temp.length()-separador).toDouble();
        x=temp.left(separador).toDouble();


        curve1.append(QPointF(x,y));
        idatos_tabla(QPointF(x,y));
        buffer_in.clear();
        ajustar_ejes();
    }

}
void smed_un::ajustar_ejes()
{
    double tmp1,tmp2;
    //QPointF m;
    //m=curve1[0];
    //maximo=double(m.ry());
    //minimo=double(m.ry());
    //for(int u=0; u<curve1.size(); u++)
    //{
      //  m=curve1[u];
        //temp1=m.ry();
        //if(maximo < temp1)
        //{
        //    maximo = double(m.ry());
        //}
        //if(minimo > temp1)
        //{
          //  minimo = double(m.ry());
        //}

    //}
    tmp1=double(curve1[curve1.size()-1].rx());
    tmp2=double(curve1[curve1.size()-1].ry());
  //  if(tmp1>maximoX){
    //    maximoX=tmp1+100;
      //  minimoX=minimoX+100;
    //}
   // if(tmp2>maximoY){
     //   maximoY=tmp2+100;
       // minimoY=tmp2-100;
    //}

    if(!curve1.empty())
    {
        seting.minY=double(curve1[0].ry());
        seting.maxY=tmp2+10;
        seting.minX=double(curve1[0].rx());
        seting.maxX=tmp1+10;
        ui->Ploter->setPlotSettings(seting);
        ui->Ploter->setCurveData(1,curve1);

    }
}
/*
void smed_un::on_checkBox_toggled(bool checked)
{

    puerto_serie->open(checked);

    statusBar()->showMessage(tr("Puerto serie: %1").arg(puerto_serie->isOpen()?"ON, Puerto: "+puerto_serie->getPort():"OFF"),2000);


    if(checked)
    {


        timer->start(global::tiempo_muestra);
    }
    else
    {
        timer->stop();

    }
}
*/
void smed_un::CapturaPortSerie()
{
    QByteArray dato;
    dato[0]=0x0A;
    puerto_serie->sendData(dato);
    statusBar()->showMessage(tr("tiempo: %1").arg(QString::number(global::tiempo_muestra)),2000);

}




void smed_un::on_Clear_graphics_clicked()
{
    curve1.clear();
    ui->Ploter->clearCurve(global::color_linea);

    for(int i=ui->tableWidget->rowCount();i>-1;i--)
    ui->tableWidget->removeRow(i);

}
void smed_un::load(){

    ui->Ploter->cargar_configuracion();
    puerto_serie->setPort(global::Puerto);
    on_Clear_graphics_clicked();
}

void smed_un::on_configurar_clicked()
{
    connect(this,SIGNAL(init_conf()),&g,SLOT(cargar_inicio()));
    emit init_conf();
    g.show();
    connect(&g,SIGNAL(configuracion_cambiada()), this, SLOT(load()));
}
void smed_un::idatos_tabla(QPointF x){

       int fila=ui->tableWidget->rowCount();

        QTableWidgetItem *item1=new QTableWidgetItem(QString::number(x.x()));
        QTableWidgetItem *item2=new QTableWidgetItem(QString::number(x.y()));

        ui->tableWidget->insertRow(ui->tableWidget->rowCount());
        ui->tableWidget->setItem(fila,0,item1);
        ui->tableWidget->setItem(fila,1,item2);


}

void smed_un::on_help_clicked()
{
    qDebug()<<"Hola mundo\ncomo estais";

}



void smed_un::on_guardar_tabla_clicked()
{
    QString temp = "";
       int n = ui->tableWidget->model()->rowCount();
       for(int i = 0; i < n; i++){
           for(int j = 0; j < 2; j++){ //4 es el numero de columnas
               QModelIndex index = ui->tableWidget->model()->index(i,j);
               temp +=  ui->tableWidget->model()->data(index).toString();
               if (j != 1)
                   temp += global::Separador_texto;

           }
           temp += "\n";
       }
       QString filename= QFileDialog::getSaveFileName(this,"guardar archivo ","Untitled.cvs", "CVS(*.cvs)");
       QFile file(filename);
       if (!file.open(QFile::WriteOnly | QFile::Text)) {
         QMessageBox::warning(this, tr("QtAvrdude"), tr("no se puede guardar el archivo:  %1:\n%2.").arg(filename).arg(file.errorString()));
         return ;
       }

       QTextStream out(&file);
       QApplication::setOverrideCursor(Qt::WaitCursor);
       out << temp.toAscii();
       QApplication::restoreOverrideCursor();
       statusBar()->showMessage(tr("File saved"), 2000);
       file.close();

}
void smed_un::guardar_configuracion(){
    qDebug()<<"Guardando Configuracion";
QSettings settings("Software Tesis.", "mdchaparror");
settings.beginGroup("smed_un");
settings.setValue("size", size());
settings.setValue("Puerto", global::Puerto);
settings.setValue("color_fondo", global::color_fondo);
settings.setValue("tiempo_muestra",QString::number(global::tiempo_muestra));
settings.setValue("color_linea",QString::number(global::color_linea));
settings.endGroup();
}
void smed_un::leer_configuracion(){
    qDebug()<<"Leyendo Configuracion \n";
QSettings settings("Software Tesis.", "mdchaparror");
settings.beginGroup("smed_un");
resize(settings.value("size", QSize(480, 360)).toSize());
global::Puerto=settings.value("Puerto").toString();
global::color_fondo=QColor(settings.value("color_fondo","white").toString());
global::tiempo_muestra=settings.value("tiempo_muestra",QString::number(500)).toInt();
global::color_linea=settings.value("color_linea",QString::number(1)).toInt();
settings.endGroup();
}

void smed_un::on_Serial_mode_clicked()
{
    qDebug()<<"cargando gui de comunicacion";
    // a=new comunicacion_serial();
    connect(&a,SIGNAL(start()),this,SLOT(start_comunicacion()));
    connect(&a,SIGNAL(stop()),this,SLOT(stop_comunicacion()));
    connect(this,SIGNAL(nuevo_dato(QString)),&a,SLOT(dato(QString)));
    a.show();
}
void smed_un::start_comunicacion(){
    puerto_serie->open(true);
    statusBar()->showMessage(tr("Puerto serie: %1").arg(puerto_serie->isOpen()?"ON, Puerto: "+puerto_serie->getPort():"OFF"),2000);
    timer->start(global::tiempo_muestra);


}
void smed_un::stop_comunicacion(){
    puerto_serie->open(false);
    statusBar()->showMessage(tr("Puerto serie: %1").arg(puerto_serie->isOpen()?"ON, Puerto: "+puerto_serie->getPort():"OFF"),2000);
    timer->stop();


}
